package com.pocketsweet.ui;

import java.util.ArrayList;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.pocketsweet.MLApplication;
import com.pocketsweet.MLContext;
import com.pocketsweet.R;
import com.pocketsweet.chat.ui.activity.BaseActivity;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.model.MLUserLike;
import com.pocketsweet.ui.uilib.AutoListView;
import com.pocketsweet.ui.uilib.HeaderLayout;
import com.pocketsweet.ui.uilib.AutoListView.OnLoadListener;
import com.pocketsweet.ui.uilib.AutoListView.OnRefreshListener;
import com.pocketsweet.ui.uilib.HeaderLayout.HeaderStyle;
import com.pocketsweet.ui.uilib.HeaderLayout.onLeftContainerListener;
import com.pocketsweet.ui.uilib.LoadingDailog;
import com.pocketsweet.ui.uilib.ViewUtil;
import com.pocketsweet.ui.uilib.adapter.LikePeopleAdapter;
import com.pocketsweet.utils.StringUtils;
import com.pocketsweet.utils.ToolKits;

@ContentView(R.layout.activity_like_poeple)
public class LikePeople extends BaseActivity implements OnRefreshListener,
		OnLoadListener, OnItemClickListener {

	private AutoListView likePeopleListview = null;
	private LikePeopleAdapter likePeopleAdapter;
	private List<MLUser> userList = new ArrayList<MLUser>();
	private List<MLUser> userLikeList = new ArrayList<MLUser>();
	private MLApplication mlApplication;
	private LinearLayout linBlank;
	private TextView tvBlankNoLove;
	private TextView tvBlankNoLover;
	private TextView tvBlankBg;
	private HeaderLayout header;
	private LoadingDailog mLoadingDialog;
	public static final int BEGIN_TO_LOADING = -1;
	private int skipDataCount = 0; // 忽略前N个对象
	public static final int MORE_DATA_MAX_COUNT = 100; // 每页10个对象
	private boolean isUpdateList = false; // 是否刷新列表

	// private BroadcastReceiver receiver = new BroadcastReceiver() {
	// @Override
	// public void onReceive(Context context, Intent intent) {
	// if (intent.getAction().equals(Main.ACTION_LIKE_POEPLE)) {
	// getUserLikerList(BEGIN_TO_LOADING);
	// likePeopleAdapter.notifyDataSetChanged();
	// }
	// }
	// };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ViewUtils.inject(this);
		mlApplication = (MLApplication) getApplication()
				.getApplicationContext();
		initView();
		setHeaderFunction();
		mLoadingDialog = ToolKits
				.createLoadingDialog(LikePeople.this, "登陆中...");
		mLoadingDialog.setText("加载中");
		getUserLikerList(AutoListView.REFRESH);

		// initListview();
	}

	private void initView() {
		// TODO Auto-generated method stub
		likePeopleListview = (AutoListView) findViewById(R.id.id_stickynavlayout_innerscrollview);
		linBlank = (LinearLayout) findViewById(R.id.linBlankNoLove);
		tvBlankNoLove = (TextView) findViewById(R.id.tvBlankNoLove);
		tvBlankBg = (TextView) findViewById(R.id.tvBlankBg);
		header = (HeaderLayout) findViewById(R.id.mainHeader);
		tvBlankNoLover = (TextView) findViewById(R.id.tvBlankNoLover);
		likePeopleAdapter = new LikePeopleAdapter(this, userList);
		likePeopleListview.setAdapter(likePeopleAdapter);
		likePeopleAdapter.notifyDataSetChanged();
		likePeopleListview.setPageSize(MORE_DATA_MAX_COUNT);
		// likePeopleListview.setOnRefreshListener(this);
		likePeopleListview.setOnLoadListener(this);
		likePeopleListview.setOnItemClickListener(this);
	}

	public void setHeaderFunction() {
		header = (HeaderLayout) findViewById(R.id.mainHeader);
		header.init(HeaderStyle.IMG_TITLE_TEXT);
		header.setRightText("");
		header.setMiddleText("喜欢的人");
		header.setLeftContainerClickListener(new onLeftContainerListener() {

			@Override
			public void onClick() {
				LikePeople.this.finish();
			}
		});
	}

	@Override
	public void onStart() {
		super.onStart();
		// IntentFilter filter = new IntentFilter();
		// filter.addAction(Main.ACTION_LIKE_POEPLE);
		// registerReceiver(receiver, filter);
	}

	/*
	 * 请求最近在线对象
	 */
	private void getUserLikerList(final int what) {
		// mLoadingDialog.show();
		linBlank.setVisibility(View.GONE);
		if (MLContext.getUserLikeSize("userSize") != -1) { // 当sharepreference有点赞纪录时从本地获取
			// Log.e("==userPreferences===", "userPreferences本地有点赞纪录");
			ArrayList<String> tempArray = new ArrayList<String>();
			ArrayList<String> userArray = new ArrayList<String>();
			tempArray = MLContext.getLike(MLContext.LIKE_TYPE_USER);
			for (String userId : tempArray) {
				if (!StringUtils.isEmpty(userId)) {
					userArray.add(userId);
					// Log.e("===userId==", "userPreferences:" + userId);
				}
			}
			if (userArray.size() <= 0) {
				likePeopleListview.setNoData();
				if (what != AutoListView.LOAD) {
					tvBlankBg.setBackgroundResource(R.drawable.blank_no_like);
					tvBlankNoLove.setText(getResources().getString(
							R.string.blank_no_like_people));
					tvBlankNoLover.setText(getResources().getString(
							R.string.blank_no_like_people_else));
					linBlank.setVisibility(View.VISIBLE);
					tvBlankNoLover.setVisibility(View.VISIBLE);
					tvBlankNoLove.setVisibility(View.VISIBLE);
					return;
				}
			}
			if (what != BEGIN_TO_LOADING) {
				isUpdateList = true; // 如果不是首次加载数据，则该动作为刷新
			} else {
				likePeopleListview.setRefreshData(); // 初始化显示loading动态图片
			}
			if (userLikeList == null || userLikeList.size() <= 0
					|| isUpdateList) { // userList为空或者动作为下拉刷新、往下加载时请求leanCloud

				final AVQuery<MLUser> query = new AVQuery<MLUser>("_User");
				skipDataCount = skipDataCount + MORE_DATA_MAX_COUNT; // 往下加载时忽略前一页
				if (what != AutoListView.LOAD) {
					skipDataCount = 0; // 刷新时不用忽略前面对象
				}
				query.whereContainedIn("objectId", userArray);
				query.setSkip(skipDataCount); // 忽略前N个
				query.limit(MORE_DATA_MAX_COUNT); // 设置每页对象个数
				query.findInBackground(new FindCallback<MLUser>() {

					@Override
					public void done(List<MLUser> userList, AVException arg1) {
						// mLoadingDialog.dismiss();
						if (arg1 == null) {
							// Log.e("===userId==",
							// "userPreferences:"
							// + String.valueOf(userList.size()));
							if (userList.size() <= 0) {
								if (what != AutoListView.LOAD) {
									tvBlankBg
											.setBackgroundResource(R.drawable.blank_no_like);
									tvBlankNoLove
											.setText(getResources()
													.getString(
															R.string.blank_no_like_people));
									tvBlankNoLover
											.setText(getResources()
													.getString(
															R.string.blank_no_like_people_else));
									linBlank.setVisibility(View.VISIBLE);
									tvBlankNoLover.setVisibility(View.VISIBLE);
									tvBlankNoLove.setVisibility(View.VISIBLE);
								}
								likePeopleListview.setNoData();

							} else {
								linBlank.setVisibility(View.GONE);

								// int listViewHeight = ViewUtil
								// .setListViewHeightBasedOnChildren1(likePeopleListview);
								switch (what) {
								case AutoListView.REFRESH: // 下拉刷新时直接重新获取数据
									userLikeList = userList;
									likePeopleListview.onRefreshComplete();
									// onLineListAdapter.setDatas(userList);
									break;
								case AutoListView.LOAD: // 加载更多时把新获取的数据添加到list列表
									likePeopleListview.onLoadComplete();
									userLikeList.addAll(userList);
									break;
								case BEGIN_TO_LOADING: // Application无数据时首次加载，即重新获取数据
									userLikeList = userList;
									likePeopleListview.onRefreshComplete();
									// onLineListAdapter.setDatas(userList);
									break;
								}
								likePeopleListview.setResultSize(userLikeList
										.size());
								likePeopleAdapter.setDatas(userLikeList);
								likePeopleAdapter.notifyDataSetChanged();
								isUpdateList = false; // 刷新完毕，设为false
							}
						} else {
							// Log.e("＝＝错误", "查询点赞错误: " + arg1.getMessage());
							likePeopleListview.setNoData();
							if (userLikeList.size() <= 0) {

								linBlank.setVisibility(View.VISIBLE);
								tvBlankNoLover.setVisibility(View.GONE);
								tvBlankBg
										.setBackgroundResource(R.drawable.network_error);
								tvBlankNoLove.setText(getResources().getString(
										R.string.blank_network_error));
								linBlank.setOnClickListener(new OnClickListener() {

									@Override
									public void onClick(View arg0) {
										getUserLikerList(BEGIN_TO_LOADING);
									}
								});
							}else{
								ToolKits.toast(LikePeople.this, "网络错误");
							}
						}
					}
				});

			} else {
				// mLoadingDialog.dismiss();
				linBlank.setVisibility(View.VISIBLE);
				tvBlankNoLover.setVisibility(View.VISIBLE);
				// userLikeList = null;
				// likePeopleAdapter.setDatas(userLikeList);
				// likePeopleAdapter.notifyDataSetChanged();
			}
		}else{
			likePeopleListview.setNoData();
			tvBlankBg.setBackgroundResource(R.drawable.blank_no_like);
			tvBlankNoLove.setText(getResources().getString(
					R.string.blank_no_like_people));
			tvBlankNoLover.setText(getResources().getString(
					R.string.blank_no_like_people_else));
			linBlank.setVisibility(View.VISIBLE);
			tvBlankNoLover.setVisibility(View.VISIBLE);
			tvBlankNoLove.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onLoad() {
		// TODO Auto-generated method stub
		getUserLikerList(AutoListView.LOAD);

	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		getUserLikerList(AutoListView.REFRESH);
		likePeopleListview.setOnRefreshListener(this);
	}
}